package com.example.liyuehui.myapplication;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ViewGroup;

/***
 *
 *
 * 横向RecyclerView嵌套viewpager
 *
 */
public class HorizontalRecyclerViewPager extends RecyclerView {
	private float startX;
	private SnapHelper snapHelper;

	public HorizontalRecyclerViewPager(Context context) {
		super(context);
		init();
	}

	public HorizontalRecyclerViewPager(Context context, @Nullable AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public HorizontalRecyclerViewPager(Context context, @Nullable AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	private void init(){
		snapHelper = new LinearSnapHelper();
		snapHelper.attachToRecyclerView(this);
	}


	@Override
	public boolean onInterceptTouchEvent(MotionEvent e) {
		int action = e.getAction();
		switch (action) {
			case MotionEvent.ACTION_DOWN:
				startX = e.getX();
				break;
			case MotionEvent.ACTION_MOVE:
//				if (intercept) return false;
				float delay = e.getX() - startX;
				Log.e("delay", "ACTION_MOVEdelay:" + delay);
				if (delay < 1) {
					LinearLayoutManager layoutManager = (LinearLayoutManager) getLayoutManager();
					int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
					ViewGroup view = (ViewGroup) layoutManager.findViewByPosition(firstVisibleItemPosition);
					ViewPager viewPager = view.findViewById(R.id.viewpager);
					if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {
						Log.e("delay", "viewPager:" + viewPager.getCurrentItem() + " count:" + viewPager.getAdapter().getCount());
						return false;
					}

				}else if(delay > 1){
					LinearLayoutManager layoutManager = (LinearLayoutManager) getLayoutManager();
					int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
					ViewGroup view = (ViewGroup) layoutManager.findViewByPosition(firstVisibleItemPosition);
					ViewPager viewPager = view.findViewById(R.id.viewpager);
					if (viewPager.getCurrentItem() > 0) {
						Log.e("delay", "viewPager:" + viewPager.getCurrentItem() + " count:" + viewPager.getAdapter().getCount());
						return false;
					}
				}
				break;
			case MotionEvent.ACTION_UP:
			case MotionEvent.ACTION_CANCEL:

		}
		Log.e("Ex", "action:" + action);
		return super.onInterceptTouchEvent(e);
	}
}
